import axios,{type AxiosResponse} from "axios";
import qs from "qs";
import Cookie from "js-cookie";
import { ElMessage } from "element-plus";
import router from "@/router";

let baseURL = '';
let host = '';
// 判断开发环境
if (process.env.NODE_ENV === "development") {
  baseURL = '/api/m.api';
  host = ''
} else {
  baseURL = 'http://zxwyit.cn:8080/m.api';
  host = 'http://zxwyit.cn:8080'
}

declare interface TyepResponse extends AxiosResponse{
  errno:number,
  errmsg:string
}

const instance = axios.create({
  baseURL,
  headers: { "content-type": "application/x-www-form-urlencoded" },
});
// 添加请求拦截器
instance.interceptors.request.use(
  function (config: any) {
    // 在发送请求之前做些什么
    if (config.headers) {
      config.headers["AdminToken"] = Cookie.get("token") + "";
    }
    return config;
  },
  function (error) {
    console.log("请求错误", error);
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response:any) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    let data = response.data;
    let { errno, errmsg } = data;
    let path = router.currentRoute.value.fullPath;
    if (10006 === errno) {
      router.replace({ path: "/login", query: { back: path } });
      ElMessage.error(errmsg);
      return;
    }
    return data;
  },
  function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    console.log("响应错误", error);
    return Promise.reject(error);
  }
);

function get(params?: object):Promise<TyepResponse> {
  return instance.get("", { params });
}
function post(data: object, params?: object):Promise<TyepResponse> {
  return instance.post("", qs.stringify(data), { params });
}
export { get, post };
